<?php

class cronGoc {

    public function start() {
        $result = $this->getHotels();
        if ($result['status']) {
            $connect = $this->connectToGoc();
            if ($connect['status']) {
                $rooms = $this->parseHotels($connect['cause'], $result['code']);
            }
        }
        return $rooms;
    }

    public function parseHotels($client, $hotels) {
        foreach ($hotels as $h) {
            echo '<div>' . $h . '</div>';
            $date = sbValues::getDateToDB();
            $r = $this->getAvalibleRoomsPerHotel($client, $h, $date);
            $xml = simplexml_load_string($r->Get_Available_RoomsResult, 'SimpleXMLElement', LIBXML_NOCDATA);
            $error = $xml->Error->Text->__toString();
            if ($error === "Not found") {
                $this->resetPrice($h, $date);
            } else {
                $rooms = $this->parseResult($xml, $h, $date);
                echo $rooms;
            }
        }

        return 'end';
    }

    public function getHotels() {
        $hotels = Doctrine_Core::getTable('tblHotel')->createQuery('e')->where('provider_id=?', sbValues::PROVIDER_GOC);

        $count = $hotels->count();
        $hotelsData = $hotels->execute();
        $provider_codes = array();
        $index = 0;
        foreach ($hotelsData as $h) {
            $provider_codes[$index] = $h->getProviderCode();
            $index++;
        }

        return array('status' => true, 'count' => $count, 'code' => $provider_codes);
    }

    public function resetPrice($hotel_id, $date) {
        $hotel = tblHotelTable::getInstance()->findByDql('provider_id=? and provider_code=?', array(sbValues::PROVIDER_GOC, $hotel_id))->getFirst();
        if ($hotel) {
            $prices = tblPriceTable::getInstance()->findByDql('hotel_id=? and period=? and date=? and type=?', array($hotel->getId(), 1, $date, 1));
            if ($prices) {
                foreach ($prices as $p) {
                    $p->setBarPriceUsd(0);
                    $p->save();
                }
            }
        }
    }

    public function parseResult($result, $hotelProviderCode, $date) {
        $hotel = tblHotelTable::getInstance()->findByDql('provider_id=? and provider_code=?', array(sbValues::PROVIDER_GOC, $hotelProviderCode))->getFirst();
        if ($hotel) {
            $prices = tblPriceTable::getInstance()->findByDql('hotel_id=? and period=? and date=? and type=?', array($hotel->getId(), 1, $date, 1));
            foreach ($prices as $p) {
                $p->setBarPriceUsd(0);
                $p->save();
            }

            foreach ($result->Rooms->Room as $room) {
                $temp = array(
                    'hotel_id' => $room->HotelID->__toString(),
                    'room_id' => $room->RoomType->__toString(),
                    'room_name' => $room->RoomName->__toString(),
                    'room_description' => $room->RoomDescription->__toString(),
                    'room_price' => $room->RoomPrice->__toString()
                );
                $room = tblRoomsTable::getInstance()->findByDql('code_name=?', $temp['room_id'])->getFirst();
                if ($room) {
                    $prices = tblPriceTable::getInstance()->findByDql('hotel_id=? and room_id=? and date=? and type=? and period=?', array($hotel->getId(), $room->getId(), $date, 1, 1))->getFirst();
                    if ($prices) {
                        $prices->setBarPriceUsd((double) $temp['room_price']);
                        $prices->save();
                    } else {
                        $this->createNewPrice($hotel->getId(), $room->getId(), $date, 1, $temp['room_price']);
                    }
                } else {
                    $this->createNewRoom($hotel->getId(), $temp['room_id'], $temp['room_name'], $temp['room_description'], $date, $temp['room_price'], 1);
                }
            }
            return 'hotel ' . $hotel->getNameEn() . ' update';
        }
        return 'hotel not found';
    }

    public function createNewRoom($hotel_id, $room_code, $name, $description, $date, $price, $type) {
        $room = new tblRooms();
        $room->setHotelId($hotel_id);
        $room->setName($name);
        $room->setCodeName($room_code);
        $room->setDescriptionEn($description);
        $room->setAdult(0);
        $room->setChildren(0);
        $room->setBaby(0);
        $room->setUpdateTime(sbValues::getCurrentTime());
        $room->setCreateTime(sbValues::getCurrentTime());
        $room->save();

        $this->createNewPrice($hotel_id, $room->getId(), $date, $type, $price);

        return true;
    }

    public function createNewPrice($hotel_id, $room_id, $date, $type, $price) {
        $prices = new tblPrice();
        $prices->setHotelId($hotel_id);
        $prices->setRoomId($room_id);
        $prices->setDate($date);
        $prices->setPeriod(1);
        $prices->setType($type);
        $prices->setBarPriceUsd((double) $price);
        $prices->setCreateTime(sbValues::getCurrentTime());
        $prices->save();

        return true;
    }

    public function connectToGoc() {
        $urlGOC = "http://webbnb.com/SilverAPI.asmx?wsdl";
        $param = array('soap_version' => SOAP_1_1, 'trace' => 1, "exceptions" => 0, 'cache_wsdl' => 0, 'login' => 'travissite', 'password' => 'travissite');
        try {
            $client = new \SoapClient(sbValues::URL_GOC_USD, $param);
            return array('status' => true, 'cause' => $client);
        } catch (SoapFault $ex) {
            return array('status' => false, 'cause' => $ex);
        }
    }

    public function getAvalibleRoomsPerHotel($client, $hotel, $date) {
        $d = explode('-', $date);
        return $client->Get_Available_Rooms(
                        array(
                            'apr' => array(
                                'DataSupplierCredentials' => array(
                                    'DataSupplierLogin' => "travissite",
                                    'DataSupplierPassword' => "travissite"
                                ),
                                'ArrivalDate' => array(
                                    'Year' => $d[0],
                                    'Month' => $d[1],
                                    'Day' => $d[2]
                                ),
                                'CustomerID' => Language::TRAVIS_USD,
                                'HotelID' => $hotel,
                                'Days' => 1,
                                'CityCode' => '',
                                'RequestRooms' => array(
                                    'Room' => array(
                                        array(
                                            'Adults' => 1,
                                            'Children' => 0,
                                            'Babies' => 0,
                                            'RoomNumber' => 1,
                                            'RoomType' => '',
                                            'MeanPlan' => '',
                                            'InternalRemarks' => ''
                                        ),
                                    ),
                                ),
                                'LanguageID' => Language::Hebrew,
                                'Currency' => Language::NIS
                            ),
                        )
        );
    }

    public function getAvailableRooms($client, $hotels) {
        return $client->Get_Available_Rooms(
                        array(
                            'apr' => array(
                                'DataSupplierCredentials' => array(
                                    'DataSupplierLogin' => "travissite",
                                    'DataSupplierPassword' => "travissite"
                                ),
                                'ArrivalDate' => array(
                                    'Year' => 2014,
                                    'Month' => 4,
                                    'Day' => 1
                                ),
                                'CustomerID' => Language::TRAVIS_NIS,
                                'HotelIDs' => $hotels,
                                'Days' => 1,
                                'CityCode' => '',
                                'RequestRooms' => array(
                                    'Room' => array(
                                        array(
                                            'Adults' => 2,
                                            'Children' => 0,
                                            'Babies' => 0,
                                            'RoomNumber' => 1,
                                            'RoomType' => '',
                                            'MeanPlan' => '',
                                            'InternalRemarks' => ''
                                        ),
                                    ),
                                ),
                                'LanguageID' => Language::Hebrew
                            ),
                        )
        );
    }

}

class Language {

    const English = 'English';
    const Hebrew = 'Hebrew';
    const TRAVIS_NIS = 219;
    const TRAVIS_USD = 163;
    const USD = 'USD';
    const NIS = 'NIS';

}
